package com.tnl.utils;

import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSONObject;
import com.tnl.app.entity.AccessToken;
import com.tnl.app.entity.WxAppUser;
import com.tnl.base.Const;
import com.tnl.base.SystemConfig;

/**
 * 微信登陆使用util
 * 
 * @author adela
 * 
 */
public class UserManagerUtil {

	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	/*
	 * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
	 * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
	 */
	public static JSONObject getAccessToken(String appId, String appSecret,
			String js_code) {
		JSONObject wat = null;
		String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
		requestUrl = requestUrl.replace("APPID", appId);
		requestUrl = requestUrl.replace("SECRET", appSecret);
		requestUrl = requestUrl.replaceAll("JSCODE", js_code);

		System.out.println("requesUrl=" + requestUrl);

		// JSONObject jsonObject = Curl.conn(requestUrl);
		JSONObject jsonObject = CommonUtil
				.httpsRequest(requestUrl, "GET", null);

		System.out.println("jsonObject=" + jsonObject);

		try {
			if (jsonObject.getString("errcode") != null) {
				String errcode = jsonObject.getString("errcode");
				System.out.println("errcoid=" + errcode);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			String a = org.apache.commons.lang.exception.ExceptionUtils
					.getFullStackTrace(e);
			wat = JSONObject.parseObject("{\"errcode exception\":\"" + a
					+ "\"}");
			return wat;
		}

		try {
			wat = jsonObject;
		} catch (Exception e) {
			String a = org.apache.commons.lang.exception.ExceptionUtils
					.getFullStackTrace(e);
			wat = JSONObject.parseObject("{\"json exception\":\"" + a + "\"}");
			String errorCode = jsonObject.getString("errcode");
			String errorMsg = jsonObject.getString("errmsg");
			e.printStackTrace();
			return wat;
		}

		return wat;
	}
	

	public static JSONObject getWxInfo(String jsCode, String iv, String encryptedData) {
		WxAppUser wxappinfo;
		String appId, appSecret;
		JSONObject jsonObject;
		String deString = null;
		appId = SystemConfig.getProperties("appid_med");
		appSecret = SystemConfig.getProperties("appscret_med");
		try {
			JSONObject aString = UserManagerUtil.getAccessToken(appId,
					appSecret, jsCode);
			if (aString != null)
				System.out.println("session_key="+ aString.getString("session_key"));
				String sessionKey = aString.getString("session_key");

			if (sessionKey == null) {
				return aString;
			}

			deString = WXBizDataCrypt.getInstance().decrypt(encryptedData,sessionKey, iv, "utf-8");
			System.out.println("destring=" + deString);

			if (deString == null) {
				return aString;
			}

			jsonObject = JSONObject.parseObject(deString);
			System.out.println("jsonobject=" + jsonObject);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			String a = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
			jsonObject = JSONObject.parseObject("{\"errcode\":\"" + a + "\"}");
			e.printStackTrace();
			deString = "error";
		}
		return jsonObject;
	}

	
	public static JSONObject getWxUserInfo(String jsCode, String iv, String encryptedData) {
		WxAppUser wxappinfo;
		String appId, appSecret;
		JSONObject jsonObject;
		String deString = null;
		appId = SystemConfig.getProperties("appid");
		appSecret = SystemConfig.getProperties("appscret");
		try {
			JSONObject aString = UserManagerUtil.getAccessToken(appId,
					appSecret, jsCode);
			if (aString != null)
				System.out.println("session_key="+ aString.getString("session_key"));
				String sessionKey = aString.getString("session_key");

			if (sessionKey == null) {
				return aString;
			}

			deString = WXBizDataCrypt.getInstance().decrypt(encryptedData,sessionKey, iv, "utf-8");
			System.out.println("destring=" + deString);

			if (deString == null) {
				return aString;
			}

			jsonObject = JSONObject.parseObject(deString);
			System.out.println("jsonobject=" + jsonObject);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			String a = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
			jsonObject = JSONObject.parseObject("{\"errcode\":\"" + a + "\"}");
			e.printStackTrace();
			deString = "error";
		}
		return jsonObject;
	}
	
	//jsonobject={"avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKUZLcGygvg3qy3dBjUBMDCmSAicgF5tLzpAZaia46zD1aqFEjtr5PEjqlf2pqsVFRg8JdiczOWypbcA/132",
	//"city":"","country":"China","gender":2,"language":"zh_CN","nickName":"蝈蝈","openId":"oP4uZ5fcKzUvzxSVT1CPTvxAo_sM","province":"",
	//"unionId":"oVCCz1Cw7iionAH55UsYlXJp0-Ss","watermark":{"appid":"wx4eac11b8af3dc297","timestamp":1531122687}}

	/**
	 * @param jsonObject
	 * @return
	 */
	public static WxAppUser getSNSUserInfo(JSONObject jsonObject){
		WxAppUser wxappUser=new WxAppUser();
        if (jsonObject!=null) {
        	try{
        		if(jsonObject.getString("errcode")!=null){
	        		String errcode=jsonObject.getString("errcode");
	        		System.out.println("errcoid="+errcode);
                    wxappUser.setErrorCode(true);      

                    return wxappUser;
        	  }
        	 }catch (Exception e) {
				// TODO: handle exception
			}
            try {
                // openid
                wxappUser.setOpenid(jsonObject.getString("openId"));
                // nickname
                wxappUser.setNickname(jsonObject.getString("nickName"));
                // gender
                wxappUser.setGender(Integer.parseInt(jsonObject.getString("gender")));
                wxappUser.setLanguage(jsonObject.getString("language"));
                wxappUser.setCountry(jsonObject.getString("country"));
                wxappUser.setProvince(jsonObject.getString("province"));
                wxappUser.setCity(jsonObject.getString("city"));
                wxappUser.setAvatar(jsonObject.getString("avatarUrl"));
                wxappUser.setUnionid(jsonObject.getString("unionId"));
                wxappUser.setUsername(jsonObject.getString("nickName"));
            } catch (Exception e) {
                wxappUser = null;
                String errorCode = jsonObject.getString("errcode");
                String errorMsg = jsonObject.getString("errmsg");
               e.printStackTrace();
            }
        }else{
        	System.out.println("json=null");
        }
        return wxappUser;
    }
	
	
	public static AccessToken getAccessToken(){
        AccessToken token = new AccessToken();
        String url = ACCESS_TOKEN_URL.replace("APPID", Const.APP_ID).replace("APPSECRET", Const.APP_SECRET);
        JSONObject jsonObject = CommonUtil
				.httpsRequest(url, "GET", null);
        if(jsonObject!=null){
            token.setToken(jsonObject.getString("access_token"));
            token.setExpiresIn(jsonObject.getInteger("expires_in"));
        }
        return token;
    }
	
}
